/**
 * author:Administrator
 * date:2016/2/25
 * desc: location 是一个深林结构, 有很多个root，每个root下是一棵树
 */

'use strict';
let Repo = require('./locationRepo.js');
let DomainModel = require('../../../lib/DomainModel.js');
let events = require('../../saga/domainEvent.js');

let ROOT_PID = 0;

class Location extends DomainModel {

  constructor() {
    super();
  }

  /**
   * 从数据库中读取，re-constructor an obj
   * @param pojo
   */
  static rebuild(pojo) {
    let entity = new Location();
    let keys = Object.keys(pojo);
    for (let key of keys) {
      entity[key] = pojo[key];
    }
    return entity;
  }

  /**
   * 新建 一个当前对象的实例
   * @param pojo, key:
   */
  static freshNew(pojo) {
    let entity = new Location();
    entity.pid = pojo.pid || ROOT_PID;
    entity.name = pojo.name;
    return entity;
  }

  * store(sagaId) {
    let isNew = !this.id;
    yield Repo.store(this);

    // pub envent if necessary
    if (isNew) {
      let event = new events.LocationCreated(sagaId, this);
      // console.log('pub event ', event);
      this.pubDomainEvent(event);
    }
  }

  * destroy(sagaId, isForce) {
    yield Repo.destroy(this.id, isForce);
    let event = new events.LocationDestroyed(sagaId, this);
    // console.log('pub event ', event);
    this.pubDomainEvent(event)
  }
}

module.exports = Location;